package com.jblog.controller.directive;

import static com.jblog.Constants.Encoding.UTF8;
import static com.jblog.Constants.Template.TPL_STYLE_LIST;
import static com.jblog.Constants.Template.TPL_SUFFIX;
import static com.jblog.common.web.freemarker.DirectiveUtils.OUT_LIST;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.jblog.common.web.freemarker.DirectiveUtils;
import com.jblog.core.model.blog.Category;
import com.jblog.core.model.blog.param.CategoryParam;
import com.jblog.core.service.facde.BlogFacade;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@SuppressWarnings({"unchecked", "rawtypes"})
public class CategoryListDirective implements TemplateDirectiveModel{
    
    @Autowired protected BlogFacade iblog;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        List<Category> list = getList(params, env);
        
        Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
        paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list));
        Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);

        env.include(TPL_STYLE_LIST + DirectiveUtils.getStyleList(params) + TPL_SUFFIX, UTF8, true);
        
        DirectiveUtils.removeParamsFromVariable(env, params, origMap);
    }

    public List<Category> getList(Map<String, TemplateModel> params,
            Environment env) throws TemplateException {
        CategoryParam categoryParam = new CategoryParam();
        categoryParam.setPositive(true);
        
        return iblog.findAllCategory(categoryParam);
    }
    
}
